package com.tang.common.utils;

import com.tang.common.entity.UserEntity;
import io.jsonwebtoken.*;

import java.util.*;

import static io.jsonwebtoken.Claims.AUDIENCE;

public class JwtUtils {
    private static final String jwtKey = "tang";

    /**
     * 加密获取令牌
     * @return token
     */
    public static String encryptForToken(String userName,String passWord){
        JwtBuilder builder = Jwts.builder();
        return builder
                // header（封装头部）
                .setHeaderParam("type", "JWT")
                .setHeaderParam("alg", "HS256")
                // payload（封装载荷）
                .claim("userName", userName)
                .claim("passWord", passWord)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 30)) //超时时间
                .setId(UUID.randomUUID().toString())
                // signature（封装签名）
                .signWith(SignatureAlgorithm.HS256, jwtKey)
                .compact();
    }

    /**
     * 解密令牌
     * @param token 令牌
     */
    public static Claims decodeToken(String token){
        JwtParser parser = Jwts.parser();
        return parser.setSigningKey(jwtKey).parseClaimsJws(token).getBody();
    }

    /**
     * 验证令牌是否正确
     */
    public static boolean verify(String token, UserEntity entity) {
        try {
            Claims claims = decodeToken(token);
            return claims.get("userName").equals(entity.getUserName()) && Md5Utils.verifyMD5WithSalt(claims.get("passWord").toString(),entity.getPassword(),entity.getSalt()) && claims.getExpiration().after(new Date());
        } catch (Exception e) {
            return false;
        }
    }

    public static String getUserNameFromToken(String token) {
        Claims claims = decodeToken(token);
        return claims.get("userName").toString();
    }

}

